package com.city.java.feedbacks.service.impl;

import com.city.java.base.utils.PageVO;
import com.city.java.feedbacks.mapper.FeedbackMapper;
import com.city.java.feedbacks.pojo.entity.Feedbacks;
import com.city.java.base.response.JsonResult;
import com.city.java.base.response.StatusCode;
import com.city.java.feedbacks.service.FeedbackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 意见反馈服务实现类
 */
@Slf4j
@Service
public class FeedbackServiceImpl implements FeedbackService {

    @Autowired
    private FeedbackMapper feedbackMapper;

    @Override
    public JsonResult addFeedback(Feedbacks feedback) {
        log.debug("准备添加反馈: {}", feedback);

        // 参数校验
        if (feedback == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "反馈信息不能为空");
        }

        if (feedback.getUserId() == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "用户ID不能为空");
        }

        if (feedback.getUserName() == null || feedback.getUserName().trim().isEmpty()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "用户姓名不能为空");
        }

        if (feedback.getContent() == null || feedback.getContent().trim().isEmpty()) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "反馈内容不能为空");
        }

        // 设置创建时间
        if (feedback.getCreatedAt() == null) {
            feedback.setCreatedAt(LocalDateTime.now());
        }

        // 设置默认状态
        if (feedback.getStatus() == null) {
            feedback.setStatus(Feedbacks.FeedbackStatus.pending);
        }

        try {
            feedbackMapper.insertFeedback(feedback);
            log.info("反馈添加成功: 反馈ID={}", feedback.getFeedbackId());
            return JsonResult.ok();
        } catch (Exception e) {
            log.error("添加反馈失败: 用户ID={}, 用户姓名={}", feedback.getUserId(), feedback.getUserName(), e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "添加反馈失败");
        }
    }

    @Override
    public JsonResult getFeedbackById(Long feedbackId) {
        log.debug("根据ID查询反馈: {}", feedbackId);

        // 参数校验
        if (feedbackId == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "反馈ID不能为空");
        }

        try {
            Feedbacks feedback = feedbackMapper.selectById(feedbackId);
            if (feedback != null) {
                log.info("查询反馈成功: ID={}", feedbackId);
                return JsonResult.ok(feedback);
            } else {
                log.warn("反馈不存在: ID={}", feedbackId);
                return new JsonResult(StatusCode.OPERATION_FAILED, "反馈不存在");
            }
        } catch (Exception e) {
            log.error("查询反馈失败: ID={}", feedbackId, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询反馈失败");
        }
    }

    @Override
    public JsonResult getFeedbacksByUserId(Long userId) {
        log.debug("根据用户ID查询反馈列表: {}", userId);

        // 参数校验
        if (userId == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "用户ID不能为空");
        }

        try {
            List<Feedbacks> feedbacks = feedbackMapper.selectByUserId(userId);
            log.info("查询用户反馈列表成功: 用户ID={}, 反馈数量={}", userId, feedbacks.size());
            return JsonResult.ok(feedbacks);
        } catch (Exception e) {
            log.error("查询用户反馈列表失败: 用户ID={}", userId, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询反馈列表失败");
        }
    }

    @Override
    public JsonResult getFeedbacksByStatus(Feedbacks.FeedbackStatus status) {
        log.debug("根据状态查询反馈列表: {}", status);

        // 参数校验
        if (status == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "状态不能为空");
        }

        try {
            List<Feedbacks> feedbacks = feedbackMapper.selectByStatus(status);
            log.info("查询状态反馈列表成功: 状态={}, 反馈数量={}", status, feedbacks.size());
            return JsonResult.ok(feedbacks);
        } catch (Exception e) {
            log.error("查询状态反馈列表失败: 状态={}", status, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询反馈列表失败");
        }
    }

    @Override
    public JsonResult getAllFeedbacks() {
        log.debug("查询所有反馈列表");

        try {
            List<Feedbacks> feedbacks = feedbackMapper.selectAll();
            log.info("查询所有反馈列表成功: 反馈数量={}", feedbacks.size());
            return JsonResult.ok(feedbacks);
        } catch (Exception e) {
            log.error("查询所有反馈列表失败", e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询反馈列表失败");
        }
    }

    @Override
    public JsonResult deleteFeedbackById(Long feedbackId) {
        log.debug("根据ID删除反馈: {}", feedbackId);

        // 参数校验
        if (feedbackId == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "反馈ID不能为空");
        }

        try {
            int result = feedbackMapper.deleteById(feedbackId);
            if (result > 0) {
                log.info("删除反馈成功: ID={}", feedbackId);
                return JsonResult.ok();
            } else {
                log.warn("删除反馈失败，反馈不存在: ID={}", feedbackId);
                return new JsonResult(StatusCode.OPERATION_FAILED, "反馈不存在");
            }
        } catch (Exception e) {
            log.error("删除反馈失败: ID={}", feedbackId, e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "删除反馈失败");
        }
    }

    @Override
    public JsonResult updateFeedback(Feedbacks feedback) {
        log.debug("更新反馈信息: {}", feedback);

        // 参数校验
        if (feedback == null || feedback.getFeedbackId() == null) {
            return new JsonResult(StatusCode.INVALID_PARAMETER, "反馈ID不能为空");
        }

        try {
            // 检查反馈是否存在
            Feedbacks existingFeedback = feedbackMapper.selectById(feedback.getFeedbackId());
            if (existingFeedback == null) {
                log.warn("更新反馈失败，反馈不存在: ID={}", feedback.getFeedbackId());
                return new JsonResult(StatusCode.OPERATION_FAILED, "反馈不存在");
            }

            int result = feedbackMapper.updateById(feedback);
            if (result > 0) {
                log.info("更新反馈成功: ID={}", feedback.getFeedbackId());
                return JsonResult.ok();
            } else {
                log.warn("更新反馈失败: ID={}", feedback.getFeedbackId());
                return new JsonResult(StatusCode.OPERATION_FAILED, "更新反馈失败");
            }
        } catch (Exception e) {
            log.error("更新反馈失败: ID={}", feedback.getFeedbackId(), e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "更新反馈失败");
        }
    }

    @Override
    public PageVO<Feedbacks> select(String username, Feedbacks.FeedbackStatus status, LocalDateTime minDate, LocalDateTime maxDate, Integer pageNum, Integer pageSize) {
        pageNum = PageVO.build(pageNum, pageSize);
        List<Feedbacks> feedbacks = feedbackMapper.select(username, status, minDate, maxDate, pageNum, pageSize);
        Long totalPage = feedbackMapper.getTotal(username, status, minDate, maxDate);

        PageVO<Feedbacks> pageVO = new PageVO<>();
        pageVO.setList(feedbacks);
        pageVO.setTotalPage(totalPage);

        log.debug("查询反馈列表成功: {}", pageVO);
        return pageVO;
    }
}
